package com.leo;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.ScheduledService;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * @ClassName ScheduledServiceDemo
 * @Description
 * @Author wangss
 * @date 2020.06.20 22:26
 * @Version 1.0
 */
public class ScheduledServiceDemo extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        AnchorPane an = new AnchorPane();
        an.setStyle("-fx-background-color: #f4fffe");

        HBox hBox = new HBox(20);
        hBox.setAlignment(Pos.CENTER);

        Button start = new Button("开始");
        Button cancel = new Button("取消");
        Button restart = new Button("重启");
        Button reset = new Button("重置");

        ProgressBar progressBar = new ProgressBar();
        progressBar.setPrefWidth(200d);
        progressBar.setProgress(0.0);

        Label state = new Label("state");
        Label value = new Label("value");
        Label title = new Label("title");
        Label message = new Label("message");

        hBox.getChildren().addAll(start, cancel, restart, reset, progressBar, state, value, title, message);

        AnchorPane.setTopAnchor(hBox, 100d);
        AnchorPane.setLeftAnchor(hBox, 10d);
        an.getChildren().addAll(hBox);
        Scene scene = new Scene(an);
        primaryStage.setScene(scene);
        primaryStage.setTitle("多任务");
        primaryStage.setWidth(800d);
        primaryStage.setHeight(800d);
        primaryStage.show();

        ScheduledService scheduledService = new MyScheduledService();
        // 开始以后延迟5s执行
        scheduledService.setDelay(Duration.seconds(5));
        // 每一秒执行一次ScheduledService的createTask方法
        scheduledService.setPeriod(Duration.seconds(1));
        // 启动失败，是否重启
        scheduledService.setRestartOnFailure(true);
        // 最大失败次数
        scheduledService.setMaximumFailureCount(4);

        start.setOnAction(event -> {
            scheduledService.start();
        });

        cancel.setOnAction(event -> {
            scheduledService.cancel();
        });

        restart.setOnAction(event -> {
            scheduledService.restart();
        });

        reset.setOnAction(event -> {
            scheduledService.reset();
        });

        scheduledService.progressProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {

            }
        });
    }
}
